#ifndef __QTXMLCONFIGURATIONBUILDER_H__
#define __QTXMLCONFIGURATIONBUILDER_H__

#include <HierarchicalConfiguration.h>

#include <QFile>
#include <QXmlDefaultHandler>
#include <QXmlInputSource>
#include <QXmlSimpleReader>

class QtXmlConfigurationBuilder : public QXmlDefaultHandler
{
 public:
    QtXmlConfigurationBuilder() 
	{
	    m_root = 0;
	    m_currentNode = m_root;
	}

    void run( const QString & uri )
	{
	    QFile file( uri );
	    file.open( QIODevice::ReadOnly );
	    QXmlInputSource source( &file );
	    QXmlSimpleReader reader;
	    reader.setContentHandler( this );

	    reader.parse( &source, false );
	}

    bool startElement ( const QString & namespaceURI, 
			const QString & localName, 
			const QString & qName, 
			const QXmlAttributes & atts 
			)
	{
	    HierarchicalConfigurationNode * node = new HierarchicalConfigurationNode( false, m_currentNode, localName.toStdString() );
	    for( int i = 0; i < atts.length(); i++ )
		node->addAttribute( atts.localName( i ).toStdString(), atts.value( i ).toStdString() );

	    if( m_currentNode == 0 )
		m_root = m_currentNode = node;
	    else
		m_currentNode->addChild( node );
	    m_currentNode = node;

	    return( true );
	}

    bool characters( const QString & ch )
	{
	    QString s = ch.trimmed();

	    if( s.isEmpty() )
		return( true );

	    if( m_currentNode != 0 )
		m_currentNode->setValue( s.toStdString() );
	    return( true );
	}

    bool endElement ( const QString & namespaceURI, 
		      const QString & localName, 
		      const QString & qName )
	{
	    if( m_currentNode->parentNode() != 0 )
		m_currentNode = m_currentNode->parentNode();

	    return( true );
	}
    
    HierarchicalConfigurationNode * m_root, * m_currentNode;
};

#endif // __QTXMLCONFIGURATIONBUILDER_H__
